package com.example.controller;

import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.example.common.Result;
import com.example.entity.User;
import com.example.entity.Account;
import com.example.service.UserService;
import com.github.pagehelper.PageInfo;
import jakarta.annotation.Resource;
import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.net.URLEncoder;
import java.util.List;

@RestController
@RequestMapping("/user")
public class UserController {

    @Resource
    private UserService userService;

    /**
     * 新增数据
     */
    @PostMapping("/add")
    public Result add(@RequestBody User user) {
        userService.add(user);
        return Result.success();
    }

    /**
     * 更新数据
     */
    @PutMapping("/update")
    public Result update(@RequestBody User user) {
        userService.update(user);
        return Result.success();
    }

    /**
     * 删除单个数据
     */
    @DeleteMapping("/deleteById/{id}")
    public Result deleteById(@PathVariable Long id) {
        userService.deleteById(id);
        return Result.success();
    }

    /**
     * 批量删除数据
     */
    @DeleteMapping("/deleteBatch")
    public Result deleteBatch(@RequestBody List<Long> ids) {
        userService.deleteBatch(ids);
        return Result.success();
    }

    /**
     * 查询单个数据
     */
    @GetMapping("/selectById/{id}")
    public Result selectById(@PathVariable Long id) {
        User user = userService.selectById(id);
        return Result.success(user);
    }

    /**
     * 查询所有的数据
     */
    @GetMapping("/selectAll")
    public Result selectAll(User user) {
        List<User> list = userService.selectAll(user);
        return Result.success(list);
    }

    /**
     * 分页查询的数据
     * pageNum: 当前页码
     * pageSize: 每页的个数
     */
    @GetMapping("/selectPage")
    public Result selectPage(User user,
                             @RequestParam(defaultValue = "1") Integer pageNum,
                             @RequestParam(defaultValue = "10") Integer pageSize) {
        PageInfo<User> pageInfo = userService.selectPage(user, pageNum, pageSize);
        return Result.success(pageInfo);
    }

    /**
     * 导出excel（修正后）
     */
    @GetMapping("/export")
    public void export(HttpServletResponse response) throws Exception {
        List<User> userList = userService.selectAll(null);
        ExcelWriter writer = ExcelUtil.getWriter(true);
        
        // 调整表头别名，匹配User实体类实际属性
        writer.addHeaderAlias("id", "用户ID");
        writer.addHeaderAlias("username", "账号");
        writer.addHeaderAlias("password", "密码");
        writer.addHeaderAlias("role", "角色");
        writer.addHeaderAlias("name", "姓名");
        writer.addHeaderAlias("phone", "手机号");
        writer.addHeaderAlias("email", "邮箱");
        writer.addHeaderAlias("create_time", "创建时间");
        
        writer.setOnlyAlias(true);  // 仅导出设置别名的字段
        writer.write(userList, true);
    
        // 输出文件配置（不变）
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8");
        String fileName = URLEncoder.encode("用户信息", "UTF-8");
        response.setHeader("Content-Disposition", "attachment;filename=" + fileName + ".xlsx");
        ServletOutputStream os = response.getOutputStream();
        writer.flush(os);
        writer.close();
    }

    /**
     * excel 导入（修正后）
     */
    @PostMapping("/import")
    public Result importData(MultipartFile file) throws Exception {
        InputStream inputStream = file.getInputStream();
        ExcelReader reader = ExcelUtil.getReader(inputStream);
        
        // 调整表头别名，匹配User实体类实际属性
        reader.addHeaderAlias("用户ID", "id");
        reader.addHeaderAlias("账号", "username");
        reader.addHeaderAlias("密码", "password");
        reader.addHeaderAlias("角色", "role");
        reader.addHeaderAlias("姓名", "name");
        reader.addHeaderAlias("手机号", "phone");
        reader.addHeaderAlias("邮箱", "email");
        reader.addHeaderAlias("创建时间", "create_time");
        
        List<User> userList = reader.readAll(User.class);
        for (User user : userList) {
            userService.add(user);  // 复用已有的添加逻辑（含唯一性校验）
        }
        return Result.success();
    }

    /**
     * 获取普通用户信息
     * @param username 用户名
     * @return 用户信息
     */
    @GetMapping("/getInfo")
    public Result getInfo(@RequestParam String username) {
        User user = userService.getByUsername(username);
        return Result.success(user);
    }

    @PutMapping("/updateInfo")
    public Result updateInfo(@RequestBody User user) {
        userService.updateInfo(user);
        return Result.success();
    }

    /**
     * 修改用户密码
     * @param user 包含用户 ID、旧密码和新密码的用户对象
     * @return 操作结果
     */
    @PutMapping("/updatePassword")
    public Result updatePassword(@RequestBody User user) {
        if (user.getId() == null) {
            return Result.error("500", "用户 ID 不能为空");
        }
        if (user.getPassword() == null || user.getNewPassword() == null) {
            return Result.error("500", "旧密码或新密码不能为空");
        }
        userService.updatePassword(user);
        return Result.success();
    }

    @PostMapping("/resetPassword")
    public Result resetPassword(@RequestBody User user) {
        userService.resetPassword(user.getId(), user.getPassword());
        return Result.success();
    }

    @PostMapping("/login")
    public Result login(@RequestBody Account account) {
        if (account.getCaptcha() == null || !account.getCaptcha().equals("2")) {
            return Result.error("500", "验证码错误");
        }
        try {
            Account loginUser = userService.login(account);
            return Result.success(loginUser);
        } catch (Exception e) {
            return Result.error("500", e.getMessage());
        }
    }
}
